<template>
    <div>
        <navbar :showHeaderIcon="true" />
        <div class="page-card">
            <el-select v-model="yearNum" placeholder="全部学年" @change="changeyear" clearable>
                <el-option
                v-for="item in yearlist"
                :key="item"
                :label="item"
                :value="item">
                </el-option>
            </el-select>
            <el-select v-model="wlfxNumber" placeholder="方向" @change="changefx">
                <el-option
                v-for="item in examFx"
                :key="item.id"
                :label="item.name"
                :value="item.id">
                </el-option>
            </el-select>
        </div>
        <div class="page-card">
            <table class="tableBox" cellspacing="0" cellpadding="0">
                <tr>
                    <th>学校</th>
                    <th>分数线</th>
                    <th>上报年</th>
                    <th v-if="wlfxNumber==0">物理方向</th>
                    <th v-if="wlfxNumber==0">历史方向</th>
                    <th v-if="wlfxNumber!=0">不区分</th>
                </tr>
                <tbody v-for="(item,index) in online" :key="index">
                    <tr>
                        <td :rowspan="item.sysOnlineAdmin.length+1">{{item.schoolName}}</td>
                    </tr>
                    <tr v-for="(child,num) in item.sysOnlineAdmin" :key="num">
                        <td>
                            {{child.fractionBarName}}
                        </td>
                        <td>
                            {{child.reportYear}}
                        </td>
                        <td v-if="wlfxNumber==0">
                            <el-input v-model="child.physicsDirection" v-if="onlineNumber&&index==0" @input="child.physicsDirection = $event.replace(/[^0-9]/g, '')"></el-input>
                            <span v-else>{{child.physicsDirection}}</span>
                        </td>
                        <td v-if="wlfxNumber==0">
                            <el-input v-model="child.historicalDirection" v-if="onlineNumber&&index==0" @input="child.historicalDirection = $event.replace(/[^0-9]/g, '')"></el-input>
                            <span v-else>{{child.historicalDirection}}</span>
                        </td>
                        <td v-if="wlfxNumber!=0">
                            <el-input v-model="child.noDistinctionNumber" v-if="onlineNumber&&index==0"  @input="child.noDistinctionNumber = $event.replace(/[^0-9]/g, '')"></el-input>
                            <span v-else>{{child.noDistinctionNumber}}</span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="page-bottom">
            <div class="addbutton">
                <el-button type="primary" @click="addYear" :disabled="addMounth>month&&!yearStatus?false:true">新增学年</el-button>
                <el-button v-if="!onlineNumber" type="primary" @click="editOnline">编辑</el-button>
                <el-button v-else type="primary" @click="sureOnline">保存</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import { Navbar } from "@/layout/components";
import { onlineManage,updateonlineManage,selectYeardate } from "@/api/xmgl/sxgl";
export default{
    name:"Lksb_sxgl",
    data(){
        return {
            allGrade:[],
            examFx:[{id:0,name:'文理方向'},{id:1,name:'不区分'}],
            online:[],
            loading: false,
            wlfxNumber:0,
            onlineNumber:false,
            month:new Date().getFullYear() + 1 +'-'+ (new Date().getMonth()-1),
            yearlist:[],
            yearNum:'',
            yearStatus:false,
            addMounth:new Date().getFullYear() +'-'+ (new Date().getMonth()-1)
        }
    },
    created(){
        this.selectyearlist()
        this.onlineManagelist()
    },
    methods:{
        //获取年级
        selectyearlist(){
            selectYeardate().then(res=>{
                console.info(res,'ressss')
                if(res.code==200){
                    this.yearlist = res.data
                }else{
                   this.$message.error(res.msg);  
                }
            })
        },
        //获取分数线列表
        onlineManagelist(){
            let obj={
                // type:this.wlfxNumber?this.wlfxNumber:undefined,
                reportYear:this.yearNum?this.yearNum:undefined
            }
            onlineManage(obj).then(res=>{
                console.info(res,'res')
                if(res.code==200){
                    let objarray=[
                        {fractionBarName:'清北线',reportYear:'2025',physicsDirection:'',historicalDirection:'',noDistinctionNumber:''},
                        {fractionBarName:'985线',reportYear:'2025',physicsDirection:'',historicalDirection:'',noDistinctionNumber:''},
                        {fractionBarName:'211线',reportYear:'2025',physicsDirection:'',historicalDirection:'',noDistinctionNumber:''},
                        {fractionBarName:'特控(一本)线',reportYear:'2025',physicsDirection:'',historicalDirection:'',noDistinctionNumber:''},
                        {fractionBarName:'本科(二本)线',reportYear:'2025',physicsDirection:'',historicalDirection:'',noDistinctionNumber:''},
                        {fractionBarName:'专科线',reportYear:'2025',physicsDirection:'',historicalDirection:'',noDistinctionNumber:''}
                    ]
                    if(res.data[0].sysOnlineAdmin.length==0){
                        res.data[0].sysOnlineAdmin = objarray
                    }
                    this.online= res.data
                    let year = new Date().getFullYear() + 1
                    const hasCurrentYear = this.online.some(school =>
                        school.sysOnlineAdmin.some(bar => Number(bar.reportYear) === year)
                    )
                    this.yearStatus = hasCurrentYear
                }else{
                    this.$message.error(res.msg);
                }
            })
        },
        changeyear(val){
            this.yearNum = val
            this.onlineManagelist()
        },
        changefx(){
            this.wlfxNumber = val
            this.onlineManagelist() 
        },
        //编辑
        editOnline(){
            this.onlineNumber = true
        },
        // 保存
        sureOnline(){
                const phySeq = []   // 仅存 physicsDirection
                const hisSeq = []   // 仅存 historicalDirection
                // for (const school of this.online) {
                    for (const bar of this.online[0].sysOnlineAdmin) {
                         // 处理空值和转换为字符串
                        const pv = bar.physicsDirection ? String(bar.physicsDirection).trim() : '';
                        const hv = bar.historicalDirection ? String(bar.historicalDirection).trim() : '';
                        // 仅检查：如果填写了内容，必须是正整数（允许为空或0）
                        if (pv && (!/^\d+$/.test(pv) || Number(pv) < 0)) {
                            this.$message({
                                message: `【${bar.fractionBarName}】物理方向必须为非负整数！`,
                                type: 'warning'
                            });
                            return;
                        }
                        if (hv && (!/^\d+$/.test(hv) || Number(hv) < 0)) {
                            this.$message({
                                message: `【${bar.fractionBarName}】历史方向必须为非负整数！`,
                                type: 'warning'
                            });
                            return;
                        }
                        // 转换为数字（空字符串转为0）
                        const pNum = pv ? Number(pv) : 0;
                        const hNum = hv ? Number(hv) : 0;

                        phySeq.push(pNum)
                        hisSeq.push(hNum)
                    }
                let lastValidPhy = null;
                for (let i = 0; i < phySeq.length; i++) {
                    const current = phySeq[i];
                    // 只处理非0值
                    if (current > 0) {
                        if (lastValidPhy !== null && current <= lastValidPhy) {
                            this.$message({
                                message: '物理方向分数必须按“清北线→专科线”顺序严格递增！',
                                type: 'warning'
                            });
                            return;
                        }
                        lastValidPhy = current;
                    }
                }

                // 历史方向分数校验：跳过0值，只校验非0值是否严格递增
                let lastValidHis = null;
                for (let i = 0; i < hisSeq.length; i++) {
                    const current = hisSeq[i];
                    // 只处理非0值
                    if (current > 0) {
                        if (lastValidHis !== null && current <= lastValidHis) {
                            this.$message({
                                message: '历史方向分数必须按“清北线→专科线”顺序严格递增！',
                                type: 'warning'
                            });
                            return;
                        }
                        lastValidHis = current;
                    }
                }
                const flatList = this.online.flatMap(school =>
                    school.sysOnlineAdmin.map(item => ({
                        ...item,
                        type: this.wlfxNumber // 这里就是你想要的“type”
                    }))
                );

            updateonlineManage(flatList).then(res=>{
                if(res.code==200){
                    this.onlineNumber = false
                    this.onlineManagelist()
                }else{
                    this.$message({
                        message: res.msg,
                        type: 'error'
                    });
                }
            })
        },
        //新增学年
        addYear(){
            let year = new Date().getFullYear() + 1
            // 只要有一个学校下任意一条 sysOnlineAdmin 的 reportYear == 当前年就认为已存在
            const hasCurrentYear = this.online.some(school =>
            school.sysOnlineAdmin.some(bar => Number(bar.reportYear) === year)
            )
            this.yearStatus = hasCurrentYear

            if (hasCurrentYear) {
                this.$message({
                    message:`${year} 年数据已存在，无法再次添加！`,
                    type: 'warning'
                });
                return 
                // 这里 return 或阻止后续添加逻辑
            }
            let objarray={
                    schoolName:this.online[0].schoolName,
                    sysOnlineAdmin:[
                        {fractionBarName:'清北线',reportYear:year,physicsDirection:'',historicalDirection:'',noDistinctionNumber:''},
                        {fractionBarName:'985线',reportYear:year,physicsDirection:'',historicalDirection:'',noDistinctionNumber:''},
                        {fractionBarName:'211线',reportYear:year,physicsDirection:'',historicalDirection:'',noDistinctionNumber:''},
                        {fractionBarName:'特控(一本)线',reportYear:year,physicsDirection:'',historicalDirection:'',noDistinctionNumber:''},
                        {fractionBarName:'本科(二本)线',reportYear:year,physicsDirection:'',historicalDirection:'',noDistinctionNumber:''},
                        {fractionBarName:'专科线',reportYear:year,physicsDirection:'',historicalDirection:'',noDistinctionNumber:''}
                    ]
                }  
                this.online.unshift(objarray)
                console.info(this.online,'this.online')
        }
    },
    components: {
        Navbar,
    },
}
</script>

<style scoped>
.page-card {
    width: 1200px;
    margin-left: auto;
    margin-right: auto;
    display: flex;
    align-items: center;
    margin-top:14px;
}
.page-card  >>> .el-select{
    margin-right:15px;
}
.tableBox{
    border-left: 1px solid #dfe6ec;
    border-top: 1px solid #dfe6ec;
    width:100%;
}
.tableBox tr th{
    word-break: break-word;
    background-color: #E8F0FA;
    color: #515a6e;
    height: 40px;
    font-size: 13px;
    border-right: 1px solid #dfe6ec;
    border-bottom: 1px solid #dfe6ec;
}
.tableBox tr td{
    word-break: break-word;
    color: #515a6e;
    height: 40px;
    font-size: 13px;
    border-right: 1px solid #dfe6ec;
    border-bottom: 1px solid #dfe6ec;
    text-align: center;
}
.tableBox tr:hover{
    background-color:#f1f1f148;
}
.addbutton{
    width:1200px;
    margin:0 auto;
}
.tableBox >>> .el-input{
    width:80px;
}
</style>
